import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QHBoxLayout, QLineEdit, QLabel, QGridLayout
from PyQt5.QtCore import Qt
from Socket_Sever import start_server, stop_server
from threading import Thread
from Socket_Client import FileSender
import os

class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # 设置按钮样式的通用样式表
        button_style_base = "min-width: 100px; max-width: 500px; min-height: 50px; font-size: 16px;"
        
        # 创建按钮和文本框
        socket_sever_start_button = QPushButton('Socket Server启动', self)
        socket_sever_start_button.setStyleSheet(f"background-color: green; color: white; {button_style_base}")
        socket_sever_start_button.clicked.connect(self.start_action)

        socket_sever_stop_button = QPushButton('Socket Server停止', self)
        socket_sever_stop_button.setStyleSheet(f"background-color: red; color: white; {button_style_base}")
        socket_sever_stop_button.clicked.connect(self.stop_action)
        
        self.path_input = QLineEdit(self)
        self.path_input.setStyleSheet("min-width: 150px; max-width: 450px; min-height: 50px; font-size: 16px; padding: 0 10px;")
        self.path_input.setPlaceholderText("请在这里输入文件夹路径")
        
        self.url_input = QLineEdit(self)
        self.url_input.setStyleSheet("min-width: 150px; max-width: 450px; min-height: 50px; font-size: 16px; padding: 0 10px;")
        self.url_input.setPlaceholderText("请在这里输入请求地址")

        socket_push_button = QPushButton('Socket向手机推送文件启动', self)
        socket_push_button.setStyleSheet(f"background-color: orange; color: white; {button_style_base}")
        socket_push_button.clicked.connect(self.file_sender)

        # 使用网格布局来确保对齐
        grid = QGridLayout()
        grid.addWidget(socket_sever_start_button, 0, 0)  # 第一行第一列
        grid.addWidget(self.path_input, 0, 1)  # 第一行第二列
        grid.addWidget(socket_sever_stop_button, 1, 0)  # 第二行第一列
        grid.addWidget(self.url_input, 1, 1)  # 第二行第二列
        grid.addWidget(socket_push_button, 2, 1)  # 第二行第二列
        
        # 设置列间距和行间距
        grid.setHorizontalSpacing(20)
        grid.setVerticalSpacing(20)

        self.setLayout(grid)

        self.setWindowTitle('PyQt5 Button Example')
        self.setGeometry(500, 300, 1000, 400)  # 设置窗口大小为600x400
        self.show()

    def start_action(self):
        print("启动按钮被按下")
        Thread(target=start_server).start()

    def stop_action(self):
        print("停止按钮被按下")
        stop_server()


        
    def progress_callback(callback_type, *args):
        """进度回调函数"""
        if callback_type == 'total_files':
           print(f"总文件数：{args[0]}")
        elif callback_type == 'file_progress':
           filename, current, total = args
           if total > 0:
              percentage = (current * 100) / total
              print(f"文件 {filename} 进度：{current}/{total} ({percentage:.2f}%)")
        elif callback_type == 'complete':
            print("传输完成")
        elif callback_type == 'error':
            print(f"错误：{args[0]}")
            
    def file_sender(self):
        print(f"文本框内容: {self.path_input.text()}")
        # 创建发送器实例
        sender = FileSender()
    
        # 设置进度回调
        sender.set_progress_callback(self.progress_callback)
    
        # 设置要传输的文件夹路径
        folder_path = self.path_input.text().strip()
        if not os.path.exists(folder_path):
           print(f"错误：文件夹 {folder_path} 不存在")
           return
    
        # 设置端口号
        port = 3000
        host = self.url_input.text().strip()
    
        print(f"\n开始传输文件夹：{folder_path}")
        print(f"请求地址：{host}:{port}")
    
        try:
            # 开始传输
            sender.send_folder(folder_path, port,host)
        except KeyboardInterrupt:
            print("\n传输被用户中断")
        except Exception as e:
            print(f"\n传输出错：{str(e)}")
        finally:
            print("传输完成")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())
